home *** CD-ROM | disk | FTP | other *** search
/ CD Actual 9 / CDACTUAL9.iso / share / Dos / VARIOS / pascal / SWAG9605.DDD / 0082_ShellExecute in Delphi2-NT.pas < prev    next >
Encoding:
Pascal/Delphi Source File  |  1996-05-31  |  2.2 KB  |  62 lines

  1. (*
  2. > David Swaddle <100657.155@CompuServe.COM> wrote:
  3. >
  4. > >Can anyone suggest a method of running an MS DOS applications
  5. > >(yuck) from within Delphi 2 where the program can be forced to
  6. > >wait for the DOS process to finish before resuming??
  7. >
  8. > >I know that this sounds like an odd request, but I have a legacy
  9. > >EXE file without the source and it runs a vital part of a system
  10. > >that I'm writing.  Previously I used the TExecFile component, but
  11. > >I don't have the source for this.  I have tried using the
  12. > >ShellExecute API call and this works fine, except that I can't
  13. > >find a way of waiting to see if the new process has terminated.
  14. >
  15. > >I'm not very au fait with the Win32 API yet, so any help
  16. > >appreciated.
  17. > This works in 1.0 and should work in 2.0
  18.  
  19.  
  20. > var
  21. >    AppHandle : THandle;
  22. > begin
  23. >    AppHandle := ShellExecute(Application.MainForm.Handlle, 'OPEN',
  24. > EXEName, Params, 'C:\PROGRAMS', SW_SHOWNORMAL);
  25. >    if AppHandle <= 32 then { Error Running Program}
  26. >       raise Exception.Create('There was a problem Running the App');
  27. >    while (GetModuleUsage(AppHandle) = 0) do
  28. >       Application.ProcessMessages;
  29. > end;
  30. >
  31. > Brad Huggins
  32.  
  33. That code will not work in Delphi 2.0 because the GetModuleUsage function
  34. doesn't exist under Win32.  You can get this behavior, however, using the
  35. Win32 CreateProcess function.  Here is a function I use to wait for another
  36. program to finish execution:
  37. *)
  38.  
  39. function CreateProcessAndWait(const AppPath, AppParams: String;
  40.                               Visibility: word): DWord;
  41. var
  42.   SI: TStartupInfo;
  43.   PI: TProcessInformation;
  44.   Proc: THandle;
  45. begin
  46.   FillChar(SI, SizeOf(SI), 0);
  47.   SI.cb := SizeOf(SI);
  48.   SI.wShowWindow := Visibility;
  49.   if not CreateProcess(PChar(AppPath), PChar(AppParams), Nil, Nil, False,
  50.                    Normal_Priority_Class, Nil, Nil, SI, PI) then
  51.     raise Exception.CreateFmt('Failed to execute program.  Error Code %d',
  52.                               [GetLastError]);
  53.   Proc := PI.hProcess;
  54.   CloseHandle(PI.hThread);
  55.   if WaitForSingleObject(Proc, Infinite) <> Wait_Failed then
  56.     GetExitCodeProcess(Proc, Result);
  57.   CloseHandle(Proc);
  58. end;
  59.